package com.github.baichuan.application.scaffold.rest.config;

import com.github.baichuan.web.dto.Result;
import com.github.baichuan.web.error.NoSuchEntityException;
import com.github.baichuan.web.valication.ValidationUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity validationErrors(MethodArgumentNotValidException ex){
        BindingResult result = ex.getBindingResult();
        Map<String, String> errors = ValidationUtils.message(result);
        return new ResponseEntity(errors, HttpStatus.BAD_REQUEST);
    }

//    @ExceptionHandler(BusinessException.class)
//    public ResponseEntity businessError(BusinessException ex){
//        Result result = Result.fail(ex.getMessage());
//        return new ResponseEntity(result, HttpStatus.NOT_ACCEPTABLE);
//    }

    @ExceptionHandler(NoSuchEntityException.class)
    public ResponseEntity noSuchEntity(NoSuchEntityException ex){
        log.warn(ex.getMessage());
        Result result = Result.fail(ex.getMessage());
        return new ResponseEntity(result, HttpStatus.NOT_FOUND);
    }



    @ExceptionHandler(Exception.class)
    public ResponseEntity defaultError(Exception ex){
        log.warn(ex.getMessage());
        Result result = Result.fail(ex.getMessage());
        return new ResponseEntity(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
